# -*- coding: UTF-8 -*-
import pytesseract
from PIL import Image

def getIdCard(path):
    #身份证号码截图
    img = Image.open(path)
    # 改变身份证尺寸
    out = img.resize((300*3,200*3),Image.ANTIALIAS)
    region = (90*3, 150*3, 280*3, 190*3)

    #裁切身份证号码图片
    cropImg = out.crop(region)
    # 转化为灰度图
    img= cropImg.convert('L')

    # 把图片变成二值图像。
    img = binary_image(img,100)
    img = delete_point(img)

    with open("./image/test.png", "wb") as f:
        img.save(f, format="png")
    exit()

    code = pytesseract.image_to_string(img, lang = 'eng')

    print ("身份证号码是:" + code)

def binary_image(img,threshold):
    pixdata = img.load()

    w, h = img.size
    for y in range(h):
        for x in range(w):
            if pixdata[x, y] < threshold:
                pixdata[x, y] = 0
            else:
                pixdata[x, y] = 255
    return img

def delete_point(img):   #input: gray image
    pixdata = img.load()
    w,h = img.size
    for y in range(1,h-1):
        for x in range(1,w-1):
            count = 0
            if pixdata[x,y-1] > 245:
                count = count + 1
            if pixdata[x,y+1] > 245:
                count = count + 1
            if pixdata[x-1,y] > 245:
                count = count + 1
            if pixdata[x+1,y] > 245:
                count = count + 1
            if count > 2:
                pixdata[x,y] = 255
    return img


if __name__ == '__main__':
    getIdCard('/var/www/html/python/image/card.png')
